package com.example.autocode.controller;

import com.example.autocode.common.R;
import com.example.autocode.model.Config;
import com.example.autocode.service.AutoCodeService;
import com.example.autocode.utils.FreeMarkerUtils;
import freemarker.template.Configuration;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

@Slf4j
@RestController
public class AutoCodeController {

    @Autowired
    AutoCodeService service;

    @PostMapping("/createTemplate")
    public R createAutocode(@RequestBody Config config) {
        String basePath = service.createAutoCode(config);
        return R.ok().data("basePath", basePath);
    }

    @GetMapping("/download")
    public void download(String basePath, HttpServletResponse response) {
        try {
            response.setContentType("application/zip");
            // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
//            String fileName = URLEncoder.encode("模板", "UTF-8");
            response.setHeader("Content-disposition", "attachment;filename=autoCode.zip");
            // 这里需要设置不关闭流
            service.write(basePath, response.getOutputStream());
            log.info("输出成功");

        } catch (Exception ex) {
            log.error("", ex);
        }
    }

}
